var rootPath = getRootPath();

$(function() {
	
	$.ajax({
		url: rootPath + '/grade/pid/0/dr/1',
        type: 'GET',
        success: function (data) {
        	if(data.returnCode == "0000") {
        		var option = "<option name='pid' value='0'>请选择级别分类</option>";
        		var length = data.returnObject.length;
        		for(var i = 0;i < length;i++) {
        			option += "<option name='pid' value='" + data.returnObject[i].gid + "'>" + data.returnObject[i].gname + "</option>";
        		}
        		$("#pGrades").append(option);
        	} else {
        		layer.alert(data.returnMessage);
        	}
        },
        error: function (jqXHR, textStatus, errorThrown) {
        	layer.alert("error:(");
        }
    });
	
	$("#gradeAddForm").validate({
		rules : {
			gname : {
				required : true,
				remote : {
					type : "GET",
					url : rootPath + "/grade/checkGname",
					data : {
						gname : function() {
							return $("#gname").val();
						}
					},
					dataFilter : function(data,type) {
						if(data == "true") {
							return true;
						} else {
							return false;
						}
					}
				}
			}
		},
		messages: {
			gname:{
				remote : "级别名称已存在"
			}
		},
		onkeyup:false,
		focusCleanup:true,
		success:"valid",
		submitHandler:function(form){
			var gname = $("#gname").val();
			var pid = $("option:selected").val();
			$.ajax({
				url: rootPath + '/grade',
	            type: 'POST',
	            data: JSON.stringify({
	            	"gname" : gname,
	            	"pid" : pid
	            }),
	            contentType: 'application/json;charset=UTF-8',
	            success: function (data) {
	            	if("0000" == data.returnCode) {	            		
	            		layer.msg('添加成功!',{icon:1,time:1000},function() {
	            			parent.window.location.href = rootPath + '/gradePage';
	            			var index = parent.layer.getFrameIndex(window.name);
	            			parent.$('.btn-refgradeh').click();
	            			parent.layer.close(index);
	            		});
	            	} else {
	            		layer.alert(data.returnMessage);
	            	}
	            },
	            error: function (jqXHR, textStatus, errorThrown) {
	            	layer.msg('error!',{icon:1,time:1000});
	            }
	        });
		}
	});
});